package com.cnzhy.jwt;

import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.crypto.MacProvider;
import org.apache.commons.codec.Charsets;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;

/**
 * @Author: zhaoyan5
 */
@SpringBootApplication
@ServletComponentScan(basePackages = "com.cnzhy")
public class SpringBootJwtApplication {

    private Key key;
    private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    @Before
    public void init() {
        String secret = "ricky"; //私钥
        byte[] apiKeySecretBytes = secret.getBytes(Charsets.UTF_8);
        key = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    }

    @Test
    public void testEncode() {
        long ttl = 7200 * 1000;
        Date now = new Date();
        Date exp = new Date(now.getTime() + ttl);
        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId("ucode").setIssuedAt(now)
                .setExpiration(exp).setSubject("sub").setIssuer("iss").setAudience("aud")
                .setHeaderParam(Header.TYPE, Header.JWT_TYPE).signWith(signatureAlgorithm, key);
        String compactJws = builder.compact();
        System.out.println(compactJws);
    }

    @Test
    public void testDecode() {
        String compactJws = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJ1Y29kZSIsImlhdCI6MTY0Njg3NTkxNiwiZXhwIjoxNjQ2ODgzMTE2LCJzdWIiOiJzdWIiLCJpc3MiOiJpc3MiLCJhdWQiOiJhdWQifQ.qadBWNafbwrxn8nI8YEuES_4DqWyKxiRR7cNRrbQn24";
        try {
            Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws).getBody();
            //OK, we can trust this JWT
            System.out.println("ID: " + claims.getId());
            System.out.println("Subject: " + claims.getSubject());
            System.out.println("Issuer: " + claims.getIssuer());
            System.out.println("Audience: " + claims.getAudience());
            System.out.println("Expiration: " + claims.getExpiration());
        } catch (SignatureException e) {
            //don't trust the JWT!
            throw e;
        }
    }

    @Test
    public void testSimple() {
        Key key = MacProvider.generateKey();
        String compactJws = Jwts.builder().setSubject("Joe").signWith(SignatureAlgorithm.HS512, key).compact();
        System.out.println(compactJws);
    }
}
